package com.maven.front.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;

public class JwtUtil {

    /**
     * token 保存时间
     */
    private static final long EXPIRE_TIME = 1000*60*15;

    /**
     * 秘匙
     */
    private static final String TOKEN_SECRET = "wyl363260858@qq.com";

    /**
     * 生成签名，15分钟后过期
     * @param username
     * @param password
     * @return
     */
    public static String sign(String username,String password) {
        //过期时间（创建时间+token保存时间）
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和id生成签名
        return JWT.create().withHeader(header).withClaim("username", username)
                .withClaim("password", password).withExpiresAt(date).sign(algorithm);
    }

    /**
     * token验证
     * @param token
     * @return
     */
    public static boolean verity(String token){
        try {
            //私钥加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
            //验证正确，返回true,否则false
        } catch (IllegalArgumentException e) {
            return false;
        } catch (JWTVerificationException e) {
            return false;
        }

    }

}
